package com.wyz.saas.common.view.airpanel

import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.wyz.saas.common.BuildConfig

class AirPanelUtils {
    companion object{
        private var DEBUG = BuildConfig.DEBUG

        fun log(format: String, vararg args: Any?) {
            if (DEBUG) Log.d("AirPanel", String.format(format, *args))
        }

        fun showKeyboard(view: View) {
            view.requestFocus()
            val inputManager =
                view.context.getSystemService(
                    Context.INPUT_METHOD_SERVICE
                ) as InputMethodManager
            inputManager.showSoftInput(view, 0)
        }

        fun hideKeyboard(view: View) {
            val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }

        fun getDefaultPanelHeight(
            context: Context,
            attribute: AirAttribute
        ): Int {
            var defaultHeight =
                ((attribute.panelMaxHeight + attribute.panelMinHeight) / 2.0f + 0.5f).toInt()
            defaultHeight = PanelSharedPreferences.get(context, defaultHeight)
            return defaultHeight
        }

        fun updateLocalPanelHeight(
            context: Context,
            height: Int
        ) {
            PanelSharedPreferences.save(context, height)
        }
    }

    private object PanelSharedPreferences {
        private const val FILE_NAME = "AirPanel.sp"
        private const val KEY_PANEL_HEIGHT = "panelHeight"

        @Volatile
        private var SP: SharedPreferences? = null
        fun save(context: Context, keyboardHeight: Int): Boolean {
            return sp(context).edit()
                .putInt(KEY_PANEL_HEIGHT, keyboardHeight)
                .commit()
        }

        private fun sp(context: Context): SharedPreferences {
            if (SP == null) {
                synchronized(PanelSharedPreferences::class.java) {
                    if (SP == null) {
                        SP = context.getSharedPreferences(
                            FILE_NAME,
                            Context.MODE_PRIVATE
                        )
                    }
                }
            }
            return SP!!
        }

        operator fun get(context: Context, defaultHeight: Int): Int {
            return sp(context).getInt(KEY_PANEL_HEIGHT, defaultHeight)
        }
    }
}